import React, { useState } from 'react';
import styles from './index.module.scss'
import { Menu, Input, Select } from 'antd';
import { ClickParam } from 'antd/lib/menu';

export interface ChangeTypeInterface {
  type: string,
  searchType: string,
  searchKey: string
}

interface PropsInterface {
  navItems: Array<string>,
  searchTypes: Array<string>,
  onChange: (obj: ChangeTypeInterface) => void
}

const initData: ChangeTypeInterface = {
  type: 'all',
  searchType: '0',
  searchKey: ''
}

const SearchBar = function (props: PropsInterface) {

  const [searchData, setSearchData] = useState({...initData})

  const navItemClick = function (item: ClickParam) { 
    const data = { ...searchData }
    data.type = item.key
    setSearchData(data)
    props.onChange(data)
  }

  const [searchDefaultType] = props.searchTypes

  const selectChange = function(value: string) {
    const data = { ...searchData }
    data.searchType = value
    setSearchData(data)
  }

  const searchBtnClick= function(val: string) {
    const data = { ...searchData }
    data.searchKey = val
    setSearchData(data)
    props.onChange(data)
  }

  const addonBefore = (
    searchDefaultType ?
    <Select onChange={selectChange} defaultValue={ searchDefaultType } style={{ width: 80 }}>
      {
        props.searchTypes.map((item: string, index: number) => {
          return <Select.Option key={ item } value={ index }>{ item }</Select.Option>
        })
      }
    </Select>
    :
    null
  );

  return <div className={ styles['com-search-bar'] }>
    <Menu onClick={navItemClick} selectedKeys={[searchData.type]} mode="horizontal">
      <Menu.Item key='all'>
        所有
      </Menu.Item>
      {
        props.navItems.map((item: string) => {
          return <Menu.Item key={item}>
            {item}
          </Menu.Item>
        })
      }
    </Menu>
    <div className={ styles['input-box'] }>
      <Input.Search onSearch={ searchBtnClick } enterButton="查询" addonBefore={addonBefore} />
    </div>
  </div>
}

SearchBar.defaultProps = {
  searchTypes: []
};

export default SearchBar
